#include "default.hpp"
#include "../models/cmd.hpp"
#include "../models/mod.hpp"
#include "../utils/template_manager.hpp"
#include "../utils/session_manager.hpp"
#include "../models/db_manager.hpp"
#include "../utils/ip_utils.hpp"
#include <sstream>
#include <iostream>
#include <jsoncpp/json/json.h>

using json = Json::Value;

bool MainController::checkSession(const crow::request& req) {
    std::string session_id;
    auto cookie_header = req.get_header_value("Cookie");
    if (!cookie_header.empty()) {
        size_t pos = cookie_header.find("session_id=");
        if (pos != std::string::npos) {
            pos += 11; // "session_id=".length()
            size_t end = cookie_header.find(";", pos);
            session_id = cookie_header.substr(pos, end - pos);
        }
    }
    
    if (session_id.empty()) {
        return false;
    }
    
    return SessionManager::getInstance().getSessionData(session_id, "db_connected") == "true";
}

void MainController::registerRoutes(crow::SimpleApp& app) {
    // 页面路由
    CROW_ROUTE(app, "/")(showLogin);
    CROW_ROUTE(app, "/login").methods("GET"_method)(showLogin);
    CROW_ROUTE(app, "/login").methods("POST"_method)(handleLogin);
    CROW_ROUTE(app, "/logout")(logout);
    
    // 首页路由
    CROW_ROUTE(app, "/db/index")([](const crow::request& req) {
        if (!MainController::checkSession(req)) {
            auto res = crow::response(302);
            res.set_header("Location", "/");
            return res;
        }
        return MainController::showIndex();
    });
    
    // API路由
    CROW_ROUTE(app, "/api/routes")
        .methods("GET"_method)
        ([](const crow::request& req) {
            if (!MainController::checkSession(req)) {
                return crow::response(401, "Unauthorized");
            }
            auto routes = Route::getAll();
            Json::Value response;
            response["status"] = "success";
            response["data"] = Json::Value(Json::arrayValue);
            
            for (const auto& route : routes) {
                Json::Value routeData;
                routeData["id"] = route.id;
                routeData["modid"] = route.modid;
                routeData["cmdid"] = route.cmdid;
                routeData["serverip"] = ip_utils::inetNtoA(route.serverip);
                routeData["serverport"] = route.serverport;
                response["data"].append(routeData);
            }
            
            Json::FastWriter writer;
            return crow::response(200, writer.write(response));
        });

    CROW_ROUTE(app, "/api/routes")
        .methods("POST"_method)
        ([](const crow::request& req) {
            if (!MainController::checkSession(req)) {
                return crow::response(401, "Unauthorized");
            }
            return MainController::handleAddRoute(req);
        });

    CROW_ROUTE(app, "/api/routes/<int>")
        .methods("PUT"_method)
        ([](const crow::request& req, int id) {
            if (!MainController::checkSession(req)) {
                return crow::response(401, "Unauthorized");
            }
            return MainController::handleUpdate(req);
        });

    CROW_ROUTE(app, "/api/routes/<int>")
        .methods("DELETE"_method)
        ([](const crow::request& req, int id) {
            if (!MainController::checkSession(req)) {
                return crow::response(401, "Unauthorized");
            }
            return MainController::handleDelete(id);
        });

    // 模块相关API
    CROW_ROUTE(app, "/api/modules")
        .methods("GET"_method)
        ([](const crow::request& req) {
            if (!MainController::checkSession(req)) {
                return crow::response(401, "Unauthorized");
            }
            auto mods = Mod::getAll();
            Json::Value response;
            response["status"] = "success";
            response["data"] = Json::Value(Json::arrayValue);
            
            for (const auto& mod : mods) {
                Json::Value modData;
                modData["id"] = mod.id;
                modData["modid"] = mod.modid;
                modData["content"] = mod.content;
                response["data"].append(modData);
            }
            
            Json::FastWriter writer;
            return crow::response(200, writer.write(response));
        });

    CROW_ROUTE(app, "/api/modules")
        .methods("POST"_method)
        ([](const crow::request& req) {
            if (!MainController::checkSession(req)) {
                return crow::response(401, "Unauthorized");
            }
            return MainController::handleAddMod(req);
        });

    // 添加模块编辑和删除的路由
    CROW_ROUTE(app, "/api/modules/<int>")
        .methods("PUT"_method)
        ([](const crow::request& req, int id) {
            if (!MainController::checkSession(req)) {
                return crow::response(401, "Unauthorized");
            }
            return MainController::editMod(req);
        });

    CROW_ROUTE(app, "/api/modules/<int>")
        .methods("DELETE"_method)
        ([](const crow::request& req, int id) {
            if (!MainController::checkSession(req)) {
                return crow::response(401, "Unauthorized");
            }
            try {
                if (Mod::remove(id)) {
                    Json::Value response;
                    response["status"] = "success";
                    response["message"] = "删除成功";
                    Json::FastWriter writer;
                    return crow::response(200, writer.write(response));
                }
                
                Json::Value response;
                response["status"] = "error";
                response["message"] = "删除失败";
                Json::FastWriter writer;
                return crow::response(400, writer.write(response));
            } catch (const std::exception& e) {
                Json::Value response;
                response["status"] = "error";
                response["message"] = std::string("删除失败: ") + e.what();
                Json::FastWriter writer;
                return crow::response(500, writer.write(response));
            }
        });

    CROW_ROUTE(app, "/db/modules/edit")
        .methods("GET"_method)
        ([](const crow::request& req) {
            if (!MainController::checkSession(req)) {
                auto res = crow::response(302);
                res.set_header("Location", "/");
                return res;
            }
            return MainController::showEditMod(req);
        });

    // 命令相关API
    CROW_ROUTE(app, "/api/commands")
        .methods("GET"_method)
        ([](const crow::request& req) {
            if (!MainController::checkSession(req)) {
                return crow::response(401, "Unauthorized");
            }
            auto cmds = Cmd::getAll();
            Json::Value response;
            response["status"] = "success";
            response["data"] = Json::Value(Json::arrayValue);
            
            for (const auto& cmd : cmds) {
                Json::Value cmdData;
                cmdData["id"] = cmd.id;
                cmdData["cmdid"] = cmd.cmdid;
                cmdData["content"] = cmd.content;
                response["data"].append(cmdData);
            }
            
            Json::FastWriter writer;
            return crow::response(200, writer.write(response));
        });

    CROW_ROUTE(app, "/api/commands")
        .methods("POST"_method)
        ([](const crow::request& req) {
            if (!MainController::checkSession(req)) {
                return crow::response(401, "Unauthorized");
            }
            return MainController::handleAddCmd(req);
        });

    // 页面路由
    CROW_ROUTE(app, "/db/routes")([](const crow::request& req) {
        if (!MainController::checkSession(req)) {
            auto res = crow::response(302);
            res.set_header("Location", "/");
            return res;
        }
        return MainController::showRouteData(req);
    });

    CROW_ROUTE(app, "/db/routes/add")([](const crow::request& req) {
        if (!MainController::checkSession(req)) {
            auto res = crow::response(302);
            res.set_header("Location", "/");
            return res;
        }
        return MainController::showAddRoute();
    });

    CROW_ROUTE(app, "/db/routes/edit")([](const crow::request& req) {
        if (!MainController::checkSession(req)) {
            auto res = crow::response(302);
            res.set_header("Location", "/");
            return res;
        }
        return MainController::showUpdateRoute(req);
    });

    CROW_ROUTE(app, "/db/modules")([](const crow::request& req) {
        if (!MainController::checkSession(req)) {
            auto res = crow::response(302);
            res.set_header("Location", "/");
            return res;
        }
        return MainController::showModid();
    });

    CROW_ROUTE(app, "/db/modules/add")([](const crow::request& req) {
        if (!MainController::checkSession(req)) {
            auto res = crow::response(302);
            res.set_header("Location", "/");
            return res;
        }
        return MainController::showAddMod();
    });

    CROW_ROUTE(app, "/db/commands")([](const crow::request& req) {
        if (!MainController::checkSession(req)) {
            auto res = crow::response(302);
            res.set_header("Location", "/");
            return res;
        }
        return MainController::showCmdid();
    });

    CROW_ROUTE(app, "/db/commands/add")([](const crow::request& req) {
        if (!MainController::checkSession(req)) {
            auto res = crow::response(302);
            res.set_header("Location", "/");
            return res;
        }
        return MainController::showAddCmd();
    });

    // 添加编辑命令页面的路由
    CROW_ROUTE(app, "/db/commands/edit")
        .methods("GET"_method)
        ([](const crow::request& req) {
            if (!MainController::checkSession(req)) {
                auto res = crow::response(302);
                res.set_header("Location", "/");
                return res;
            }
            return MainController::showEditCmd(req);
        });

    // 添加更新命令的 API 路由
    CROW_ROUTE(app, "/api/commands/<int>")
        .methods("PUT"_method)
        ([](const crow::request& req, int id) {
             if (!MainController::checkSession(req)) {
                return crow::response(401, "Unauthorized");
            }
            // 注意：editCmd 需要接收 id，但当前实现是从 req.body 获取 id
            // 这里暂时保持调用 editCmd(req)，但需要后续确认 editCmd 的实现是否正确处理 id
            return MainController::editCmd(req); 
        });

    // 添加删除命令的 API 路由
    CROW_ROUTE(app, "/api/commands/<int>")
        .methods("DELETE"_method)
        ([](const crow::request& req, int id) {
            if (!MainController::checkSession(req)) {
                return crow::response(401, "Unauthorized");
            }
            // 直接传入 id 给 deleteCmd 处理
            return MainController::deleteCmd(id);
        });

    // 状态相关API
    CROW_ROUTE(app, "/api/status")
        .methods("GET"_method)
        ([](const crow::request& req) {
            if (!MainController::checkSession(req)) {
                return crow::response(401, "Unauthorized");
            }
            try {
                auto statuses = Status::getAll();
                Json::Value response;
                response["status"] = "success";
                response["data"] = Json::Value(Json::arrayValue);
                
                for (const auto& status : statuses) {
                    Json::Value statusData;
                    statusData["modid"] = status.modid;
                    statusData["cmdid"] = status.cmdid;
                    statusData["ip"] = ip_utils::inetNtoA(status.ip);
                    statusData["port"] = status.port;
                    statusData["caller"] = ip_utils::inetNtoA(status.caller);
                    statusData["success_count"] = status.success_count;
                    statusData["error_count"] = status.error_count;
                    statusData["timestamp"] = status.timestamp;
                    statusData["is_overload"] = status.is_overload;
                    response["data"].append(statusData);
                }
                
                Json::FastWriter writer;
                return crow::response(200, writer.write(response));
            } catch (const std::exception& e) {
                Json::Value response;
                response["status"] = "error";
                response["message"] = std::string("获取状态失败: ") + e.what();
                Json::FastWriter writer;
                return crow::response(500, writer.write(response));
            }
        });

    // 页面路由
    CROW_ROUTE(app, "/db/routes/changes")([](const crow::request& req) {
        if (!MainController::checkSession(req)) {
            auto res = crow::response(302);
            res.set_header("Location", "/");
            return res;
        }
        return MainController::showRouteChange();
    });

    CROW_ROUTE(app, "/db/routes/versions")([](const crow::request& req) {
        if (!MainController::checkSession(req)) {
            auto res = crow::response(302);
            res.set_header("Location", "/");
            return res;
        }
        return MainController::showVersion();
    });

    // 路由变更相关API
    CROW_ROUTE(app, "/api/routes/changes")
        .methods("GET"_method)
        ([](const crow::request& req) {
            if (!MainController::checkSession(req)) {
                return crow::response(401, "Unauthorized");
            }
            auto changes = RouteChange::getAll();
            Json::Value response;
            response["status"] = "success";
            response["data"] = Json::Value(Json::arrayValue);
            
            for (const auto& change : changes) {
                Json::Value changeData;
                changeData["id"] = change.id;
                changeData["modid"] = change.modid;
                changeData["cmdid"] = change.cmdid;
                changeData["time"] = change.time;
                response["data"].append(changeData);
            }
            
            Json::FastWriter writer;
            return crow::response(200, writer.write(response));
        });

    // 版本信息相关API
    CROW_ROUTE(app, "/api/routes/versions")
        .methods("GET"_method)
        ([](const crow::request& req) {
            if (!MainController::checkSession(req)) {
                return crow::response(401, "Unauthorized");
            }
            auto versions = Version::getAll();
            Json::Value response;
            response["status"] = "success";
            response["data"] = Json::Value(Json::arrayValue);
            
            for (const auto& version : versions) {
                Json::Value versionData;
                versionData["id"] = version.id;
                versionData["version"] = version.version;
                versionData["time"] = version.time;
                response["data"].append(versionData);
            }
            
            Json::FastWriter writer;
            return crow::response(200, writer.write(response));
        });
}

crow::response MainController::showLogin() {
    std::map<std::string, std::string> data;
    auto response = crow::response(200, TemplateManager::getInstance().render("login.html", data));
    response.set_header("Content-Type", "text/html; charset=utf-8");
    return response;
}

crow::response MainController::handleLogin(const crow::request& req) {
    try {
        // 手动解析POST数据
        std::map<std::string, std::string> params;
        std::string body = req.body;
        size_t pos = 0;
        while ((pos = body.find('&')) != std::string::npos) {
            std::string param = body.substr(0, pos);
            size_t eq_pos = param.find('=');
            if (eq_pos != std::string::npos) {
                std::string key = param.substr(0, eq_pos);
                std::string value = param.substr(eq_pos + 1);
                
                // URL解码
                std::string decoded_value;
                for (size_t i = 0; i < value.length(); ++i) {
                    if (value[i] == '+') {
                        decoded_value += ' ';
                    } else if (value[i] == '%' && i + 2 < value.length()) {
                        std::string hex = value.substr(i + 1, 2);
                        char ch = std::stoi(hex, nullptr, 16);
                        decoded_value += ch;
                        i += 2;
                    } else {
                        decoded_value += value[i];
                    }
                }
                
                params[key] = decoded_value;
            }
            body.erase(0, pos + 1);
        }
        // 处理最后一个参数
        if (!body.empty()) {
            size_t eq_pos = body.find('=');
            if (eq_pos != std::string::npos) {
                std::string key = body.substr(0, eq_pos);
                std::string value = body.substr(eq_pos + 1);
                
                // URL解码
                std::string decoded_value;
                for (size_t i = 0; i < value.length(); ++i) {
                    if (value[i] == '+') {
                        decoded_value += ' ';
                    } else if (value[i] == '%' && i + 2 < value.length()) {
                        std::string hex = value.substr(i + 1, 2);
                        char ch = std::stoi(hex, nullptr, 16);
                        decoded_value += ch;
                        i += 2;
                    } else {
                        decoded_value += value[i];
                    }
                }
                
                params[key] = decoded_value;
            }
        }
        
        std::string dbAddr = params["dbAddr"];
        std::string dbPort = params["dbPort"];
        std::string dbUser = params["dbUser"];
        std::string dbPwd = params["dbPwd"];
        std::string dbName = params["dbName"];
        
        if (dbAddr.empty() || dbPort.empty() || dbUser.empty() || dbPwd.empty() || dbName.empty()) {
            std::map<std::string, std::string> data;
            data["errmsg"] = "输入数据不完整";
            return crow::response(400, TemplateManager::getInstance().render("login.html", data));
        }
        
        // 初始化数据库连接
        if (!DBManager::getInstance().connect(dbAddr, dbPort, dbUser, dbPwd, dbName)) {
            std::map<std::string, std::string> data;
            data["errmsg"] = "数据库连接失败";
            return crow::response(400, TemplateManager::getInstance().render("login.html", data));
        }
        
        // 创建会话
        std::string session_id = SessionManager::getInstance().createSession();
        SessionManager::getInstance().setSessionData(session_id, "db_connected", "true");
        
        crow::response res(302);
        res.set_header("Location", "/db/index");
        res.add_header("Set-Cookie", "session_id=" + session_id + "; Path=/; HttpOnly");
        return res;
    } catch (const std::exception& e) {
        std::map<std::string, std::string> data;
        data["errmsg"] = std::string("登录失败: ") + e.what();
        return crow::response(500, TemplateManager::getInstance().render("login.html", data));
    }
}

crow::response MainController::logout() {
    crow::response res(302);
    res.set_header("Location", "/login");
    res.add_header("Set-Cookie", "session_id=; Path=/; HttpOnly; Max-Age=0");
    return res;
}

crow::response MainController::showRouteData(const crow::request& req) {
    // 检查是否是AJAX请求
    if (req.get_header_value("X-Requested-With") == "XMLHttpRequest") {
        auto routes = Route::getAll();
        Json::Value response;
        response["status"] = "success";
        response["data"] = Json::Value(Json::arrayValue);
        
        for (const auto& route : routes) {
            Json::Value routeData;
            routeData["id"] = route.id;
            routeData["modid"] = route.modid;
            routeData["cmdid"] = route.cmdid;
            routeData["serverip"] = ip_utils::inetNtoA(route.serverip);
            routeData["serverport"] = route.serverport;
            response["data"].append(routeData);
        }
        
        Json::FastWriter writer;
        return crow::response(200, writer.write(response));
    }
    
    // 非AJAX请求，返回HTML页面
    std::map<std::string, std::string> data;
    data["errmsg"] = "";
    return crow::response(200, TemplateManager::getInstance().render("routeData.html", data));
}

crow::response MainController::handleDelete(int id) {
    Json::Value response;
    try {
        if (Route::remove(id)) {
            response["status"] = "success";
            response["message"] = "删除成功";
            Json::FastWriter writer;
            return crow::response(200, writer.write(response));
        } else {
            response["status"] = "error";
            response["message"] = "删除失败，请检查日志";
            Json::FastWriter writer;
            return crow::response(400, writer.write(response));
        }
    } catch (const std::exception& e) {
        std::cerr << "MainController::handleDelete - Exception: " << e.what() << std::endl;
        response["status"] = "error";
        response["message"] = std::string("删除路由时发生服务器内部错误: ") + e.what();
        Json::FastWriter writer;
        return crow::response(500, writer.write(response));
    }
}

crow::response MainController::showAddRoute() {
    std::map<std::string, std::string> data;
    return crow::response(200, TemplateManager::getInstance().render("add.html", data));
}

crow::response MainController::handleAddRoute(const crow::request& req) {
    try {
        // 解析JSON数据
        auto json = crow::json::load(req.body);
        if (!json) {
            Json::Value response;
            response["status"] = "error";
            response["message"] = "Invalid JSON";
            Json::FastWriter writer;
            return crow::response(400, writer.write(response));
        }

        // 获取参数
        int modid = json["modid"].i();
        int cmdid = json["cmdid"].i();
        std::string serverip = json["serverip"].s();
        int serverport = json["serverport"].i();
        
        if (!ip_utils::isValidIp(serverip)) {
            Json::Value response;
            response["status"] = "error";
            response["message"] = "IP地址格式错误";
            Json::FastWriter writer;
            return crow::response(400, writer.write(response));
        }
        
        uint32_t ip_int = ip_utils::inetAtoN(serverip);
        if (Route::add(modid, cmdid, ip_int, serverport)) {
            RouteChange::insert(modid, cmdid);
            Version::update();
            
            Json::Value response;
            response["status"] = "success";
            response["message"] = "添加成功";
            Json::FastWriter writer;
            return crow::response(200, writer.write(response));
        }
        
        Json::Value response;
        response["status"] = "error";
        response["message"] = "添加失败";
        Json::FastWriter writer;
        return crow::response(400, writer.write(response));
    } catch (const std::exception& e) {
        Json::Value response;
        response["status"] = "error";
        response["message"] = std::string("添加失败: ") + e.what();
        Json::FastWriter writer;
        return crow::response(500, writer.write(response));
    }
}

crow::response MainController::showUpdateRoute(const crow::request& req) {
    auto params = crow::query_string(req.url_params);
    int id = std::stoi(params.get("id"));
    
    auto route = Route::getById(id);
    std::map<std::string, std::string> data;
    data["id"] = std::to_string(route.id);
    data["modid"] = std::to_string(route.modid);
    data["cmdid"] = std::to_string(route.cmdid);
    data["serverip"] = ip_utils::inetNtoA(route.serverip);
    data["serverport"] = std::to_string(route.serverport);
    
    return crow::response(200, TemplateManager::getInstance().render("update.html", data));
}

crow::response MainController::handleUpdate(const crow::request& req) {
    try {
        // 解析JSON数据
        auto json = crow::json::load(req.body);
        if (!json) {
            Json::Value response;
            response["status"] = "error";
            response["message"] = "Invalid JSON";
            Json::FastWriter writer;
            return crow::response(400, writer.write(response));
        }

        // 获取参数
        int id = json["id"].i();
        int modid = json["modid"].i();
        int cmdid = json["cmdid"].i();
        std::string serverip = json["serverip"].s();
        int serverport = json["serverport"].i();
        
        if (!ip_utils::isValidIp(serverip)) {
            Json::Value response;
            response["status"] = "error";
            response["message"] = "IP地址格式错误";
            Json::FastWriter writer;
            return crow::response(400, writer.write(response));
        }
        
        uint32_t ip_int = ip_utils::inetAtoN(serverip);
        if (Route::update(id, modid, cmdid, ip_int, serverport)) {
            RouteChange::insert(modid, cmdid);
            Version::update();
            Json::Value response;
            response["status"] = "success";
            response["message"] = "更新成功";
            Json::FastWriter writer;
            return crow::response(200, writer.write(response));
        }
        
        Json::Value response;
        response["status"] = "error";
        response["message"] = "更新失败";
        Json::FastWriter writer;
        return crow::response(400, writer.write(response));
    } catch (const std::exception& e) {
        Json::Value response;
        response["status"] = "error";
        response["message"] = std::string("更新失败: ") + e.what();
        Json::FastWriter writer;
        return crow::response(500, writer.write(response));
    }
}

crow::response MainController::showRouteChange() {
    try {
        std::map<std::string, std::string> data;
        data["errmsg"] = "";
        return crow::response(200, TemplateManager::getInstance().render("showChange.html", data));
    } catch (const std::exception& e) {
        std::cout << "错误: " << e.what() << std::endl;
        std::map<std::string, std::string> data;
        data["errmsg"] = std::string("获取路由变更记录失败: ") + e.what();
        return crow::response(500, TemplateManager::getInstance().render("showChange.html", data));
    }
}

crow::response MainController::showVersion() {
    try {
        std::map<std::string, std::string> data;
        data["errmsg"] = "";
        return crow::response(200, TemplateManager::getInstance().render("showVersion.html", data));
    } catch (const std::exception& e) {
        std::cout << "错误: " << e.what() << std::endl;
        std::map<std::string, std::string> data;
        data["errmsg"] = std::string("获取版本信息失败: ") + e.what();
        return crow::response(500, TemplateManager::getInstance().render("showVersion.html", data));
    }
}

crow::response MainController::showCmdid() {
    auto cmdids = Cmd::getAll();
    std::map<std::string, std::string> data;
    data["errmsg"] = cmdids.empty() ? "当前无子模块ID说明信息" : "";
    
    std::stringstream ss;
    for (const auto& cmd : cmdids) {
        ss << "<tr>";
        ss << "<td>" << cmd.cmdid << "</td>";
        ss << "<td>" << cmd.content << "</td>";
        ss << "<td class='actions'>";
        ss << "<a href='/db/commands/edit?id=" << cmd.id << "' class='btn btn-sm btn-primary'>编辑</a> ";
        ss << "<button onclick='deleteCmd(" << cmd.id << ")' class='btn btn-sm btn-danger'>删除</button>";
        ss << "</td>";
        ss << "</tr>";
    }
    data["cmd_rows"] = ss.str();
    
    return crow::response(200, TemplateManager::getInstance().render("cmdid.html", data));
}

crow::response MainController::showModid() {
    auto modids = Mod::getAll();
    std::map<std::string, std::string> data;
    data["errmsg"] = modids.empty() ? "当前无模块ID说明信息" : "";
    
    std::stringstream ss;
    for (const auto& mod : modids) {
        ss << "<tr>";
        ss << "<td>" << mod.modid << "</td>";
        ss << "<td>" << mod.content << "</td>";
        ss << "<td class='actions'>";
        ss << "<a href='/db/modules/edit?id=" << mod.id << "' class='btn btn-sm btn-primary'>编辑</a> ";
        ss << "<button onclick='deleteMod(" << mod.id << ")' class='btn btn-sm btn-danger'>删除</button>";
        ss << "</td>";
        ss << "</tr>";
    }
    data["mod_rows"] = ss.str();
    
    return crow::response(200, TemplateManager::getInstance().render("modid.html", data));
}

crow::response MainController::showAddMod() {
    std::map<std::string, std::string> data;
    return crow::response(200, TemplateManager::getInstance().render("addMod.html", data));
}

crow::response MainController::showAddCmd() {
    std::map<std::string, std::string> data;
    data["errmsg"] = "";
    auto response = crow::response(200, TemplateManager::getInstance().render("addCmd.html", data));
    response.set_header("Content-Type", "text/html; charset=utf-8");
    return response;
}

crow::response MainController::handleAddMod(const crow::request& req) {
    try {
        // 解析JSON数据
        auto json = crow::json::load(req.body);
        if (!json) {
            Json::Value response;
            response["status"] = "error";
            response["message"] = "Invalid JSON";
            Json::FastWriter writer;
            return crow::response(400, writer.write(response));
        }

        // 获取参数
        int modid = json["modid"].i();
        std::string content = json["content"].s();
        
        if (content.empty()) {
            Json::Value response;
            response["status"] = "error";
            response["message"] = "模块说明不能为空";
            Json::FastWriter writer;
            return crow::response(400, writer.write(response));
        }
        
        if (Mod::exists(modid)) {
            Json::Value response;
            response["status"] = "error";
            response["message"] = "该模块ID已存在";
            Json::FastWriter writer;
            return crow::response(400, writer.write(response));
        }
        
        if (Mod::add(modid, content)) {
            Json::Value response;
            response["status"] = "success";
            response["message"] = "添加成功";
            Json::FastWriter writer;
            return crow::response(200, writer.write(response));
        }
        
        Json::Value response;
        response["status"] = "error";
        response["message"] = "添加失败";
        Json::FastWriter writer;
        return crow::response(400, writer.write(response));
    } catch (const std::exception& e) {
        Json::Value response;
        response["status"] = "error";
        response["message"] = std::string("添加失败: ") + e.what();
        Json::FastWriter writer;
        return crow::response(500, writer.write(response));
    }
}

crow::response MainController::handleAddCmd(const crow::request& req) {
    try {
        // 解析JSON数据
        auto json = crow::json::load(req.body);
        if (!json) {
            Json::Value response;
            response["status"] = "error";
            response["message"] = "Invalid JSON";
            Json::FastWriter writer;
            return crow::response(400, writer.write(response));
        }

        // 获取参数
        int cmdid = json["cmdid"].i();
        std::string content = json["content"].s();

        if (content.empty()) {
            Json::Value response;
            response["status"] = "error";
            response["message"] = "命令说明不能为空";
            Json::FastWriter writer;
            return crow::response(400, writer.write(response));
        }

        if (Cmd::exists(cmdid)) {
            Json::Value response;
            response["status"] = "error";
            response["message"] = "该子模块ID已存在";
            Json::FastWriter writer;
            return crow::response(400, writer.write(response));
        }

        if (Cmd::add(cmdid, content)) {
            Json::Value response;
            response["status"] = "success";
            response["message"] = "添加成功";
            Json::FastWriter writer;
            return crow::response(200, writer.write(response));
        }

        Json::Value response;
        response["status"] = "error";
        response["message"] = "添加失败";
        Json::FastWriter writer;
        return crow::response(400, writer.write(response));
    } catch (const std::exception& e) {
        Json::Value response;
        response["status"] = "error";
        response["message"] = std::string("添加失败: ") + e.what();
        Json::FastWriter writer;
        return crow::response(500, writer.write(response));
    }
}

crow::response MainController::deleteMod(const crow::request& req) {
    try {
        auto params = crow::query_string(req.url_params);
        int id = std::stoi(params.get("id"));
        
        if (Mod::remove(id)) {
            Json::Value response;
            response["status"] = "success";
            response["message"] = "删除成功";
            Json::FastWriter writer;
            return crow::response(200, writer.write(response));
        }
        
        Json::Value response;
        response["status"] = "error";
        response["message"] = "删除失败";
        Json::FastWriter writer;
        return crow::response(400, writer.write(response));
    } catch (const std::exception& e) {
        Json::Value response;
        response["status"] = "error";
        response["message"] = std::string("删除失败: ") + e.what();
        Json::FastWriter writer;
        return crow::response(500, writer.write(response));
    }
}

crow::response MainController::deleteCmd(int id) {
    Json::Value response;
    try {
        if (Cmd::remove(id)) {
            response["status"] = "success";
            response["message"] = "删除成功";
            Json::FastWriter writer;
            return crow::response(200, writer.write(response));
        } else {
            response["status"] = "error";
            response["message"] = "删除失败，请检查日志";
            Json::FastWriter writer;
            return crow::response(400, writer.write(response));
        }
    } catch (const std::exception& e) {
        std::cerr << "MainController::deleteCmd - Exception: " << e.what() << std::endl;
        response["status"] = "error";
        response["message"] = std::string("删除时发生服务器内部错误: ") + e.what();
        Json::FastWriter writer;
        return crow::response(500, writer.write(response));
    }
}

crow::response MainController::showEditMod(const crow::request& req) {
    auto params = crow::query_string(req.url_params);
    int id = std::stoi(params.get("id"));
    
    auto mod = Mod::getById(id);
    std::map<std::string, std::string> data;
    data["id"] = std::to_string(mod.id);
    data["modid"] = std::to_string(mod.modid);
    data["content"] = mod.content;
    return crow::response(200, TemplateManager::getInstance().render("editMod.html", data));
}

crow::response MainController::showEditCmd(const crow::request& req) {
    auto params = crow::query_string(req.url_params);
    int id = std::stoi(params.get("id"));
    
    auto cmd = Cmd::getById(id);
    std::map<std::string, std::string> data;
    data["id"] = std::to_string(cmd.id);
    data["cmdid"] = std::to_string(cmd.cmdid);
    data["content"] = cmd.content;
    return crow::response(200, TemplateManager::getInstance().render("editCmd.html", data));
}

crow::response MainController::editMod(const crow::request& req) {
    try {
        // 解析JSON数据
        auto json = crow::json::load(req.body);
        if (!json) {
            Json::Value response;
            response["status"] = "error";
            response["message"] = "Invalid JSON";
            Json::FastWriter writer;
            return crow::response(400, writer.write(response));
        }

        // 获取参数
        int id = json["id"].i();
        std::string content = json["content"].s();
        
        if (content.empty()) {
            Json::Value response;
            response["status"] = "error";
            response["message"] = "模块说明不能为空";
            Json::FastWriter writer;
            return crow::response(400, writer.write(response));
        }
        
        if (Mod::update(id, content)) {
            Json::Value response;
            response["status"] = "success";
            response["message"] = "更新成功";
            Json::FastWriter writer;
            return crow::response(200, writer.write(response));
        }
        
        Json::Value response;
        response["status"] = "error";
        response["message"] = "更新失败";
        Json::FastWriter writer;
        return crow::response(400, writer.write(response));
    } catch (const std::exception& e) {
        Json::Value response;
        response["status"] = "error";
        response["message"] = std::string("更新失败: ") + e.what();
        Json::FastWriter writer;
        return crow::response(500, writer.write(response));
    }
}

crow::response MainController::editCmd(const crow::request& req) {
    try {
        // 解析JSON数据
        auto json = crow::json::load(req.body);
        if (!json) {
            Json::Value response;
            response["status"] = "error";
            response["message"] = "Invalid JSON";
            Json::FastWriter writer;
            return crow::response(400, writer.write(response));
        }

        // 获取参数
        int id = json["id"].i();
        std::string content = json["content"].s();
        
        if (content.empty()) {
            Json::Value response;
            response["status"] = "error";
            response["message"] = "命令说明不能为空";
            Json::FastWriter writer;
            return crow::response(400, writer.write(response));
        }
        
        if (Cmd::update(id, content)) {
            Json::Value response;
            response["status"] = "success";
            response["message"] = "更新成功";
            Json::FastWriter writer;
            return crow::response(200, writer.write(response));
        }
        
        Json::Value response;
        response["status"] = "error";
        response["message"] = "更新失败";
        Json::FastWriter writer;
        return crow::response(400, writer.write(response));
    } catch (const std::exception& e) {
        Json::Value response;
        response["status"] = "error";
        response["message"] = std::string("更新失败: ") + e.what();
        Json::FastWriter writer;
        return crow::response(500, writer.write(response));
    }
}

crow::response MainController::showIndex() {
    std::map<std::string, std::string> data;
    data["errmsg"] = ""; // 初始化错误消息
    data["status"] = "[]"; // 初始化一个空的状态列表
    auto response = crow::response(200, TemplateManager::getInstance().render("index.html", data));
    response.set_header("Content-Type", "text/html; charset=utf-8");
    return response;
}

void MainController::getModList() {
    auto modids = Mod::getAll();
    Json::Value response;
    response["status"] = "success";
    response["data"] = Json::Value(Json::arrayValue);
    
    for (const auto& mod : modids) {
        Json::Value modData;
        modData["id"] = mod.id;
        modData["modid"] = mod.modid;
        modData["content"] = mod.content;
        response["data"].append(modData);
    }
    
    Json::FastWriter writer;
    response_ = writer.write(response);
}

void MainController::getCmdList() {
    auto cmdids = Cmd::getAll();
    Json::Value response;
    response["status"] = "success";
    response["data"] = Json::Value(Json::arrayValue);
    
    for (const auto& cmd : cmdids) {
        Json::Value cmdData;
        cmdData["id"] = cmd.id;
        cmdData["cmdid"] = cmd.cmdid;
        cmdData["content"] = cmd.content;
        response["data"].append(cmdData);
    }
    
    Json::FastWriter writer;
    response_ = writer.write(response);
}

// 其他方法的实现... 